package udp;

import java.io.IOException;
import java.net.*;
import java.util.Scanner;

public class UdpClient {
    private DatagramSocket socket=null;
    public UdpClient() throws SocketException {
        //构建Socket对象与服务器不同的是服务器的端口一般由系统自动分配
        socket=new DatagramSocket();
    }

    public void start() throws IOException {
        while(true){
            System.out.println("请输入你的请求：");
            Scanner scanner=new Scanner(System.in);
            String request=scanner.next();

            //将输入的请求打包为一个数据报,要指明接收该数据包的服务器(地址+端口号)
            DatagramPacket requestPacket=new DatagramPacket(request.getBytes(),0,
                    request.getBytes().length, InetAddress.getByName("127.0.0.1"), 8000);

            //发送请求数据报
            socket.send(requestPacket);
            //构造用于接收响应数据报数据的缓存数据报
            DatagramPacket responPacket=new DatagramPacket(new byte[1024],1024);

            //接收响应数据报(缓存数据报接收)
            socket.receive(responPacket);
            //解析响应数据报中的内容(注意第3个参数的选择[详情参考服务器代码])
            String respon=new String(responPacket.getData(),0,responPacket.getLength());

            System.out.println(respon);
        }

    }

    public static void main(String[] args) throws IOException {
        UdpClient client=new UdpClient();
        client.start();
    }
}
